import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { RedisService } from 'nestjs-redis';
import { ObjectType } from '../../types/obj-type';

@Injectable()
export class RedisUtilsService {
  public client: Redis;
  constructor(private redisService: RedisService) {}

  onModuleInit(): void {
    this.getClient();
  }

  public getClient() {
    this.client = this.redisService.getClient();
  }

  /**
   * 设置redis存储
   * @param key
   * @param value
   * @param second 时间
   */
  public async set(
    key: string,
    value: ObjectType | string,
    second?: number,
  ): Promise<void> {
    value = JSON.stringify(value);
    // 没有传时间就使用默认时间
    if (!second) {
      await this.client.setex(key, 24 * 60 * 60, value); // 以秒为单位
    } else {
      await this.client.set(key, value, 'EX', second);
    }
  }

  // 获取
  public async get(key: string): Promise<any> {
    const data = await this.client.get(key);
    return data ? JSON.parse(data) : null;
  }

  // 删除
  public async del(key: string): Promise<any> {
    await this.client.del(key);
  }

  // 清空redis缓存
  public async flushall(): Promise<any> {
    await this.client.flushall();
  }
}
